package com.yz.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yz.entity.CommentEntity;
import com.yz.entity.UserEntity;
import com.yz.mapper.CommentMapper;
import com.yz.service.ICommentService;
import com.yz.vo.CommentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentEntity> implements ICommentService {

    @Autowired
    private LikeService likeService;

    public boolean save(CommentEntity commentEntity){
        commentEntity.setCreateTime(new Date());
        commentEntity.setStatus(1);
        return baseMapper.insert(commentEntity) > 0;
    }

    public List<CommentVo> commentListByInvitataionId(UserEntity userEntity,Integer id) throws Exception{
        List<CommentVo> commentVoList= baseMapper.commentListByInvitataionId(1,id);
        for (CommentVo commentVo :commentVoList){
            long invitataionLikeCount = likeService.getInvitataionLikeCount(2,commentVo.getCommentEntity().getId());
            commentVo.setLikeCount(invitataionLikeCount);
            commentVo.setLikeStatus(0);
            if (userEntity != null) {
                // 已经登录了，查询当前用户是否对评论点赞了
                Boolean invitataionUserLike = likeService.getInvitataionUserLike(2, userEntity.getId(), commentVo.getCommentEntity().getId());
                commentVo.setLikeStatus(invitataionUserLike ? 1 : 0);
            }
            Integer cid = commentVo.getCommentEntity().getId();

            // 查询评论下面的回复
            List<CommentVo> replyList = baseMapper.commentListByInvitataionId(2, cid);

            // 遍历查询每个回复的点赞的数量
            for (CommentVo replyVo : replyList) {
                Long count = likeService.getInvitataionLikeCount(2, replyVo.getCommentEntity().getId());
                replyVo.setLikeCount(count);
                if (userEntity != null) {
                    // 已经登录了，查询当前用户是否对评论点赞了
                    Boolean invitataionUserLike = likeService.getInvitataionUserLike(2, userEntity.getId(), replyVo.getCommentEntity().getId());
                    replyVo.setLikeStatus(invitataionUserLike ? 1 : 0);
                }
            }
            commentVo.setReplyList(replyList); // 评论下面的回复列表
        }
        return commentVoList;

    }

}
